#!/bin/bash
#初始化参数信息,LogsPath需要清理的日志文件夹，支持多个路径用;号分割，RunsPath清理脚本所放置的路径
LogsPath="/data/apache-tomcat-9.0.76/logs;/data/apache-tomcat-9.0.76/logs_bak"
RunsPath="/data"
echo "系统自动清理日志脚本启动...【配置清理路径】:"$LogsPath" 【运行脚本所在路径】:"$RunsPath >> $RunsPath'/'autoCleanLogs.log

# 清理多少天前的日志,清理规则是按最后修改时间
CleanTime=10

LogsPathArr=(${LogsPath//;/ })

loopNum=0
for LogPath in ${LogsPathArr[@]}
do
  loopNum=$(($loopNum+1))
  echo $loopNum'-当前待清理日志目录:【'${LogPath}'】' >> $RunsPath'/'autoCleanLogs.log

  # 将catalina日志清空
  cp $LogPath/catalina.err $LogPath/catalina_"`date +%Y%m%d_%H%M%S`".err
  truncate -s 0 $LogPath/catalina.err

  cp $LogPath/catalina.out $LogPath/catalina_"`date +%Y%m%d_%H%M%S`".out
  truncate -s 0 $LogPath/catalina.out

  echo $loopNum"特殊catalina日志清空完成..." >> $RunsPath'/'autoCleanLogs.log

  # 查找30天前的logs文件夹或文件并删除
  find $LogPath -mtime +${CleanTime} -name "*.*" -exec rm -Rf {} \;

  echo $loopNum'【'${LogPath}'】'${CleanTime}'天前的日志清空完成' >> $RunsPath'/'autoCleanLogs.log
done

autoCleanLogsName=$(basename $0)
echo "当前清理脚本路径:"$RunsPath'/'$autoCleanLogsName >> $RunsPath'/'autoCleanLogs.log

#将清理结果记录到历史文件
echo Run at `date "+%Y-%m-%d %H:%M:%S"` Succ... >> $RunsPath'/'autoCleanLogs.log

#设置每天晚上11点半启动执行删除脚本
echo "自动检查&设置定时器..."
if [ ! -e /var/spool/cron/$USER ];then
	mkdir -p /var/spool/cron/
	touch /var/spool/cron/$USER
	echo "定时器文件创建完成..."
fi

if [ `grep -v '^\s*#' /var/spool/cron/$USER |grep -c $autoCleanLogsName` -eq 0 ];then
  # 每天晚上11:30自动清理日志的时间表达式:30 23 * * *
	echo "30 23 * * *"' '$RunsPath'/'$autoCleanLogsName >> /var/spool/cron/$USER
	echo "已经将任务写入定时器..."
fi